# coding:gbk
#!/usr/bin/env python
from __future__ import unicode_literals
import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from whoosh_helper import pdf_whoosh

filetype = '.pdf'

class fileEventHandler(FileSystemEventHandler):

    def __init__(self):
        FileSystemEventHandler.__init__(self)

    def on_modified(self, event):
        src = event.src_path
        if os.path.isfile(src) and os.path.splitext(src)[1] == filetype:
            pdf_whoosh.save(src)
            print ('%s has been modified' % src)

    def on_deleted(self, event):
        src = event.src_path
        if not event.is_directory and os.path.splitext(src)[1] == filetype:
            pdf_whoosh.remove(src)
            print ('%s has been deleted' % src)

class dirdog(object):

    def __init__(self, paths):
        self.threads = []
        self.paths = paths
        self.observer = Observer()
        event_handler = fileEventHandler()

        for i in self.paths:
            targetPath = str(i)
            self.observer.schedule(event_handler, targetPath, recursive=True)
            self.threads.append(self.observer)
        self.observer.start()

    def run(self):
        try:
            while 1:
                time.sleep(1)
        except KeyboardInterrupt:
            self.observer.stop()
        self.observer.join()

def main():
    from mongoer import dbobjects
    watch_path = dbobjects.settings.find_one({'name':'watch_dir'})['value']
    dog = dirdog([watch_path])
    dog.run()

if __name__ == "__main__":
    main()




